/* Copyright (c) 2004-2024 peigen.info. All rights reserved. */

package info.peigen.hotpot.manage.core.service.processor.active;

import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.core.enums.Symbol;
import info.peigen.hotpot.common.service.base.ServiceOrderBase;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import info.peigen.hotpot.manage.core.domain.Role;
import info.peigen.hotpot.manage.core.domain.User;
import info.peigen.hotpot.manage.core.service.order.LoginOrder;
import info.peigen.hotpot.manage.core.service.order.RoleEditOrder;
import info.peigen.hotpot.manage.core.service.order.UserEditOrder;
import info.peigen.hotpot.manage.core.service.processor.AbstractHotpotManageServiceProcessor;
import org.noear.solon.annotation.Component;

import java.util.List;

/**
 * <b>(RoleActiveProcessor)</b>
 * "角色" 激活处理器
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2024-06-28
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Component
public class RoleActiveProcessor extends AbstractHotpotManageServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 23;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        switchOrder(serviceContext);
    }

    private void switchOrder(ProcessorServiceContext serviceContext) {
        ServiceOrderBase contextOrder = serviceContext.getOrder();
        if (contextOrder instanceof RoleEditOrder order) {
            Role domain = roleRepository.active(order.getRoleId());
            serviceContext.setDomain(domain);
        } else if (contextOrder instanceof UserEditOrder order && StrUtil.isNotEmpty(order.getOrganizationIds())) {
            List<Role> roles = roleRepository.active(StrUtil.split(order.getRoleIds(), Symbol.COMMA.code()));
            serviceContext.getExtend().put("roles", roles);
        } else if (contextOrder instanceof LoginOrder order) {
            User         domain  = (User) serviceContext.getDomain();
            List<String> roleIds = domain.getRoles().stream().map(Role::getRoleId).toList();
            List<Role>   roles   = roleRepository.active(roleIds);
            domain.setRoles(roles);
            serviceContext.getExtend().put("roles", roles);
        }
    }

}